package com.example.test.servive.impl;

import com.example.test.model.Room;
import com.example.test.servive.ChatService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class ChatServiceImpl implements ChatService {

    private static final Map<String, Room> roomMap = new HashMap<>();

    public String joinRoom(String roomId, String userId) {
        Room room = roomMap.get(roomId);
        if (room == null) {
            synchronized (this) {
                room = roomMap.computeIfAbsent(roomId, Room::new);
            }
        }
        if(room.getMembers().contains(userId)){
            room.leaveRoom(userId);
            printMembers(roomId);
            room.joinRoom(userId);
            return "您已加入房间，请勿重复加入";
        }
        printMembers(roomId);
        room.joinRoom(userId);
        return "加入成功";
    }

    public String leaveRoom(String roomId, String userId) {
        Room room = roomMap.get(roomId);
        if (room == null) {
            return "房间不存在";
        }
        if(!room.getMembers().contains(userId)){
            printMembers(roomId);
            return "您未加入房间";
        }
        room.leaveRoom(userId);
        printMembers(roomId);

        if (room.getMembers().isEmpty()) {
            synchronized (this){
                if (roomMap.get(roomId) != null) {
                    roomMap.remove(roomId);
                }
            }
        }
        return "退出成功";
    }

    private void printMembers(String roomId) {
        Room room = roomMap.get(roomId);
        Set<String> members = room.getMembers();
        if (members.isEmpty()) {
            System.out.println("房间" + roomId + "无人");
        } else {
            System.out.println("房间" + roomId + "成员有:" + members);
        }
    }
}
